﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Diagnostics;
using Communergy.Common;
using Communergy.Common.Events;

namespace CurrentCostLibrary
{

    public class CurrentCostDevice : IEnergyMonitorProvider
    {
        public int BaudRate { get; set; }
        public string Port { get; set; }

        private SerialPort serialPort;

       // public delegate void NewEnergyReadingHandler(object sender, EnergyReadingEventArgs re);
        public event NewEnergyReadingHandler EnergyReading;



        private void RaiseNewReadingEvent(EnergyReadingEventArgs re)
        {
            if (EnergyReading!=null)
            {
                EnergyReading(this, re);
            }
        }

        public void StartReadings()
        {
            try
            {
                serialPort = new SerialPort { BaudRate = this.BaudRate, PortName = Port };
                serialPort.DataReceived += serialPort_DataReceived;
                serialPort.Open();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        /// <summary>
        /// Handles the DataReceived event of the serialPort control.
        /// </summary>
        /// <param Name="sender">The source of the event.</param>
        /// <param Name="e">The <see cref="System.IO.Ports.SerialDataReceivedEventArgs"/> instance containing the event data.</param>
        void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {

            try
            {
                
                string input = serialPort.ReadLine();
                bool useLocalTime = true;//TODO - get from config
                var newReading = ReadingParser.GetCurrentCostOutput(DateTime.Today, input, useLocalTime);
                if (newReading != null)
                {
                    RaiseNewReadingEvent(new EnergyReadingEventArgs { EnergyMonitorOutput = newReading });
                }
               
            }
            catch (Exception ex)
            {
                //TODO - remove UI call in CurrentCost reader
               Console.WriteLine(ex.Message);
            }
        }

        public void EndReadings()
        {
            try
            {
                serialPort.Close();
            }
            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);
            }
        }

 
    }
}
